package com.lagou.edu.service;

import com.lagou.edu.domain.AuthCode;
import com.lagou.edu.client.EmailService;
import com.lagou.edu.repository.AuthCodeRepository;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Random;

/**
 * Created by shixi  on 2021/1/28
 */
@Service
public class AuthCodeServiceImpl {

    @Autowired
    private AuthCodeRepository authCodeRepository;

    @Autowired
    private EmailService emailService;

    //过期时间：毫秒
    @Value("${authcode.expiretime}")
    private Long expiretime;


    public boolean createAndSend(String email) {
        if (StringUtils.isEmpty(email)){
            return false;
        }
        //发送验证码
        String code = buildCode();
        boolean con = emailService.send(email,code);
        //保存验证码数据
        if (con) {
            AuthCode authCode = new AuthCode();
            authCode.setEmail(email);
            authCode.setCode(code);
            Date date = new Date();
            authCode.setCreatetime(date);
            authCode.setExpiretime( new Date(date.getTime()+expiretime) );
            authCodeRepository.saveAndFlush(authCode);
            return true;
        }
        return false;
    }

    //生成验证码
    private String buildCode() {
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for(int i=0;i<6;i++){
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }

    //0正确1错误2超时
    public int validate(String email, String code) {
        AuthCode authCode = authCodeRepository.findByEmailAndCode(email,code);
        if(authCode==null){
            return 1;
        }
        Date expiretime = authCode.getExpiretime();
        if ((System.currentTimeMillis() - expiretime.getTime()) >= 0) {//过期
            return 2;
        }
        return 0;
    }
}
